package com.wit.example.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
* 将提取字符串中的数据并写入csv文件的工具类
*
* @Author liaozhaoping
* @Date 2024/5/10 11:42
*/

public class StringToCSV {
    public static void ToCSV(String data,File internalStorageDir,String deviceName) throws IOException {
        // 创建 CSV 文件写入器
        // 根据设备名称创建 CSV 文件名
        String filename = deviceName.replaceAll("\\s+", "_") + "_data.csv";
        File csvFile = new File(internalStorageDir, filename);


        // File csvFile = new File(internalStorageDir, "data.csv");

        // 以追加模式打开 CSV 文件
        FileWriter writer = new FileWriter(csvFile, true);// true 表示追加模式

        // 定义正则表达式模式，用于提取数据
        Pattern pattern = Pattern.compile("([\\u4e00-\\u9fa5]+[XYZ]):\\s*(-?\\d+(?:\\.\\d+)?)[\\u00B0gμT]+");

        // 获取当前时间戳
        long timestamp = System.currentTimeMillis();

        // 解析数据并写入 CSV 文件
        String[] lines = data.split("\n");
        StringBuilder csvLine = new StringBuilder(String.valueOf(timestamp));
        for (int i = 1; i < lines.length; i++) {
            Matcher matcher = pattern.matcher(lines[i]);
            while (matcher.find()) {
                csvLine.append(" ").append(matcher.group(2));
            }
        }
        writer.write(csvLine.toString());
        writer.write("\n");

        // 关闭写入器
        writer.close();
    }


    /**
    * 获取手环的一行数据
    *
    * @Author liaozhaoping
    * @Date 2024-08-23 14:41
    */

    public static String getWitData(String deviceData){
        Pattern pattern = Pattern.compile("([\\u4e00-\\u9fa5]+[XYZ]):\\s*(-?\\d+(?:\\.\\d+)?)[\\u00B0gμT]+");

        // 获取当前时间戳
        long timestamp = System.currentTimeMillis();

        // 解析数据并写入 CSV 文件
        String[] lines = deviceData.split("\n");
        StringBuilder csvLine = new StringBuilder(String.valueOf(timestamp));
        for (int i = 1; i < lines.length; i++) {
            Matcher matcher = pattern.matcher(lines[i]);
            while (matcher.find()) {
                csvLine.append(" ").append(matcher.group(2));
            }
        }
        return  csvLine.toString();
    }

}
